#include "timeval.h"

void tv_normalize(struct timeval* tv_)
{
	if (tv_->tv_usec >= ACE_ONE_SECOND_IN_USECS)
	{
		do
		{
			tv_->tv_sec++;
			tv_->tv_usec -= ACE_ONE_SECOND_IN_USECS;
		} while (tv_->tv_usec >= ACE_ONE_SECOND_IN_USECS);
	}
	else if (tv_->tv_usec <= -ACE_ONE_SECOND_IN_USECS)
	{
		do
		{
			tv_->tv_sec--;
			tv_->tv_usec += ACE_ONE_SECOND_IN_USECS;
		} while (tv_->tv_usec <= -ACE_ONE_SECOND_IN_USECS);
	}

	if (tv_->tv_sec >= 1 && tv_->tv_usec < 0)
	{
		tv_->tv_sec--;
		tv_->tv_usec += ACE_ONE_SECOND_IN_USECS;
	}
	else if (tv_->tv_sec < 0 && tv_->tv_usec >0)
	{
		tv_->tv_sec++;
		tv_->tv_usec -= ACE_ONE_SECOND_IN_USECS;
	}
}


unsigned long to_msec(struct timeval tv_)
{
	return (unsigned long)tv_.tv_sec * 1000 + tv_.tv_usec / 1000;
}

struct timeval tv_msec(unsigned long milliseconds)
{
	struct timeval tv_;
	tv_.tv_sec = milliseconds / 1000;
	tv_.tv_usec = (milliseconds - (tv_.tv_sec * 1000)) * 1000;
	return tv_;
}


struct timeval tv_gettimeofday()
{
	struct timeval t;
	struct timezone tz;
	gettimeofday(&t, &tz);
	return t;

}

struct timeval tv_add(struct timeval tv1, struct timeval tv2)
{
	struct timeval sum;
	sum.tv_sec = tv1.tv_sec + tv2.tv_sec;
	sum.tv_usec = tv1.tv_usec + tv2.tv_usec;
	tv_normalize(&sum);
	return sum;
}
struct timeval tv_sub(struct timeval tv1, struct timeval tv2)
{
	struct timeval delta;
	delta.tv_sec = tv1.tv_sec - tv2.tv_sec;
	delta.tv_usec = tv1.tv_usec - tv2.tv_usec;
	tv_normalize(&delta);
	return delta;

}
int tv_bigthan(struct timeval tv1, struct timeval tv2)
{
	if (tv1.tv_sec > tv2.tv_sec)
	{
		return 1;
	}
	else if (tv1.tv_sec == tv2.tv_sec && tv1.tv_usec > tv2.tv_usec)
	{
		return 1;
	}
	return 0;
}